package fregat.connector.channel;

import fregat.base.net.TCPClient;
import fregat.base.util.Logger;
import fregat.connector.ConnectorService;

import java.io.PrintStream;

/**
 * TCP/IP channel for a client.
 *
 * @author Alexander Mann <br><b><i>ECO_L O G</i> &nbsp Logistiksysteme GmbH</b>
 * @version 1.0
 */
public class ClientChannel extends TCPChannel {

  /**
   * Creates a new client channel that is trying to connect to the specified
   * server.
   *
   * @param name Configuration name of channel
   */
  public ClientChannel(String name) {
    super(name, false);

    // configuration -->
    String hostname = ConnectorService.getConfiguration().getConfigurationString("channel.config." + name + ".hostname");
    if (hostname == null) {
      hostname = "localhost";
    }
    int port = ConnectorService.getConfiguration().getConfigurationInteger("channel.config." + name + ".port");
    System.out.println(ConnectorService.resource.getString("ClientChannel_constructor_1") + " " + hostname + "@" + port);
    // <--

    createClient(hostname, port, name);
    client.setProtocol(ConnectorService.getConfiguration().configureProtocol(name));
  }

  /**
   * Creates a new client channel with the given hostname, port and name.
   * Use this constructor, if you use <code>ClientChannel</code> standalone.
   *
   * @param hostname
   * @param port
   * @param name
   */
  public ClientChannel(String hostname, int port, String name) {
    super(name, true);
    createClient(hostname, port, name);
  }

  private void createClient(String hostname, int port, String name) {
    client = new TCPClient(hostname, port, Logger.getCategory(ConnectorService.LOGGING_CATEGORY)) {
      protected void received(byte[] receivedData, PrintStream out) {
        ClientChannel.this.received(receivedData);
      }

      protected void connected() {
        ClientChannel.this.connected(true);
        super.connected();
      }

      public void disconnect() {
        ClientChannel.this.connected(false);
        super.disconnect();
      }
    };
    client.setName(name);
  }

  /**
   * Stops all connected listeners and the client channel.
   */
  public void shutdown() {
    client.shutdown();
    super.shutdown();
  }

  /**
   * Starts the client channel and the connected listeners.
   */
  public void start() {
    super.start();
    client.start();
  }  
}
